﻿<%@ Page Title="" Language="C#" MasterPageFile="~/PromotionPage.Master" AutoEventWireup="true"
    CodeBehind="PromotionDocumentPropertyInclusive.aspx.cs" Inherits="PromotionEngine.PromotionDocumentPropertyInclusive" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPromotionPage" runat="server">
    <script type="text/javascript">
        var oPromotionDocumentPropertyInclude = {};
        var oDoc = {};
        var oDocPropertyDetail = {};
        var isInsert = false;
        var gird;
        var girdDetail;
        var propertyForDetailID = 0;
        var promotionID  = 0;
        var referenceName;
        var checkedIds = {};
         function updateLink()
         {
                var checked = this.checked,
                row = $(this).closest("tr"),
                dataItem = gridDetail.dataItem(row);
                checkedIds[dataItem.id] = checked;
                if (checked) {
            row.addClass("k-state-selected");

                    isInsert =true;
                    } else {
                      isInsert =false;
            row.removeClass("k-state-selected");
                }
               var items = $("#gridDetail").data("kendoGrid").dataSource.data();
                  dataItem.set('LineID', checked);
                oPromotionDocumentPropertyInclude.PromotionID = promotionID;
                oPromotionDocumentPropertyInclude.PropertyDetailID = dataItem.PropertyDetailID;
                 //Update or Insert
                    UpdatePropertyLink(isInsert);
         }
          function updateRadio(e)
         {
                //Delete All
                 row = $(e).closest("tr");
                  var dataItem = gridDetail.dataItem(row);
                 var oTest=[];
                     var items = gridDetail.dataSource.data();
                    for (i = 0; i < items.length; i++) {
                      oPromotionDocumentPropertyInclude = {};
                        var item = items[i];
                        isInsert = false;   
                    oPromotionDocumentPropertyInclude.PromotionID = promotionID;
                    oPromotionDocumentPropertyInclude.PropertyDetailID = item.PropertyDetailID
                    oTest.push(oPromotionDocumentPropertyInclude);
                     item.set('LineID', '');
                  }
                        $.ajax({
                        type: "POST",
                     url: "PromotionDocumentPropertyInclusive.aspx/UpdateDocumentPropertyIncludeList",
                        data: JSON.stringify({
                            oPromotionDocumentPropertyInclude: JSON.stringify(oTest),
                            isInsert: false
                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                        //Insert new 
                         var checked = e.checked;
                         row.addClass("k-state-selected");
                         isInsert = true;
                         dataItem.set('LineID', checked);
                         oPromotionDocumentPropertyInclude.PromotionID = promotionID;
                         oPromotionDocumentPropertyInclude.PropertyDetailID = dataItem.PropertyDetailID;
                         //Update or Insert
                         UpdatePropertyLink(isInsert);
                        },
                        error: function (xhr, status, err) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
         }
        //Load Detail
        function onChange(arg) {
         var selectedRows = this.select();
            var selectedDataItems = [];
            for (var i = 0; i < selectedRows.length; i++) {
              var dataItem = this.dataItem(selectedRows[i]);
              selectedDataItems.push(dataItem);
            }
            //Set ID
            propertyForDetailID = selectedDataItems[0].PropertyID;
        
             
            referenceName =selectedDataItems[0].ReferenceName; 
             
             //Load Grid
//             var headerTemplate='<input type="checkbox" id="checkAll" onclick="updateAll(this)"/>';
//             var template="<input type='checkbox'  class='check-box'  #= LineID ? 'checked=checked' : '' # enabled='' />";
//            if(referenceName == 'Single Value')
//             {
//               headerTemplate='';
//               template="<input type='radio' name='link'  class='radio-box' onchange='updateRadio(this)'  #= LineID ? 'checked=checked' : '' # enabled='' />";
//             }
//             else if(referenceName == 'Multi Value')
//             {
//                  headerTemplate='<input type="checkbox" id="checkAll" onclick="updateAll(this)"/>'; 
//            
//             }
//             else if(referenceName = 'Free Text')
//             {
//             }
//               var columnsConfig = [];
//                columnsConfig.push({ title: '', headerTemplate: headerTemplate, template: template ,width:50 });
//                            columnsConfig.push({ field: "PropertyDetailID", title: "Property Detail ID", width: 100, hidden: true });
//                             columnsConfig.push({ field: "LineID", title: "Line ID", width: 100, hidden: true });
//                            columnsConfig.push({ field: "PropertyDetailCode", title: "Property Detail Code", width: 200, hidden: true });
//                            columnsConfig.push({ field: "PropertyDetailName", title: "Detail", width: 270});
//                    $("#gridDetail").data("kendoGrid").setOptions({
//                        columns: columnsConfig
//                    });
               
               gridDetail.dataSource.read();
               //gridDetail.table.on("click", ".check-box" , updateLink);
            
           }
            
           function UpdatePropertyLink(insert)
           {
                               $.ajax({
                        type: "POST",
                        url: "PromotionDocumentPropertyInclusive.aspx/UpdateDocumentPropertyInclude",
                        data: JSON.stringify({
                            oPromotionDocumentPropertyInclude: JSON.stringify(oPromotionDocumentPropertyInclude),
                            isInsert: insert
                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            
                        },
                        error: function (xhr, status, err) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
           }
           function updateAll(cb)
           {
           var oTest=[];
            var checked = cb.checked
             var items = $("#gridDetail").data("kendoGrid").dataSource.data();
            for (i = 0; i < items.length; i++) {
              oPromotionDocumentPropertyInclude = {};
            
                var item = items[i];
                 var checkedItem = item.LineID;
                    if(checked)
                    {
                        isInsert = true;
                    }
                    else
                    {
                        isInsert = false;   
                    }
                    oPromotionDocumentPropertyInclude.PromotionID = promotionID;
                    oPromotionDocumentPropertyInclude.PropertyDetailID = item.PropertyDetailID
                     oTest.push(oPromotionDocumentPropertyInclude);
                     if(isInsert && checkedItem!='true')
                     {
                            item.set('LineID', checked);
                     }
                     else{
                         item.set('LineID', checked);
                     }
                  }
                     //Update or Insert
                        $.ajax({
                        type: "POST",
                        url: "PromotionDocumentPropertyInclusive.aspx/UpdateDocumentPropertyIncludeList",
                        data: JSON.stringify({
                            oPromotionDocumentPropertyInclude: JSON.stringify(oTest),
                            isInsert: checked
                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            
                        },
                        error: function (xhr, status, err) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
           }
        $(document).ready(function () {
             promotionID = $('#<%=lblPromotionID.ClientID%>').val();
            var promotionCode = $('#<%=lblPromotionCode.ClientID%>').text();
            var promotionName = $('#<%=lblPromotionName.ClientID%>').text();
           $("#MasterPromotionCode").val(promotionCode);
            $("#MasterPromotionName").val(promotionName);
            $("#MasterPromotionID").val(promotionID);
            //Load Grid
            grid = $("#grid").kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                           type: "GET",
                            url: "Doc-Property.aspx/GetDocPropertys",
                            data: '',
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                        },
                        serverPaging: true,
                        serverSorting: true,
                        serverFiltering: true
                    },
                    type: "odata", //Important!!!!
                    schema: {
                        data: "d.Data",
                        total: "d.Count",
                        model: {
                            id: "PropertyID",
                            fields: {
                                PropertyID: { type: "string" },
                                PropertyCode: { type: "string" },
                                PropertyName: { type: "string" }
                            }
                        }
                    }
                },
                change: onChange,
                sortable: true,
                resizable: true,
                height: 380,
                selectable: "row",
                toolbar: [ { name: 'excel'}],
                excel: {
                    fileName: "Doc Property List.xlsx",
                    filterable: true
                },
                batch: true,
                columns: [
                            { field: "PropertyID", title: "Property ID", width: 100, hidden: true },
                            { field: "PropertyCode", title: "Property Code", width: 200, hidden: true },
                            { field: "PropertyName", title: "Property", width: 320}
                            ]
            }).data("kendoGrid");

              //Load Grid
             
            gridDetail = $("#gridDetail").kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                           type: "GET",
                            url: "PromotionDocumentPropertyInclusive.aspx/GetDocumentPropertyInclude",
                            data: '',
                            contentType: "application/json; charset=utf-8",
                            dataType: "json"
                        },
                          parameterMap: function (data, operation) {
                            if (operation === "read") {
                                return {  promotionID:promotionID ,propertyID: propertyForDetailID };
                            }
                        },
                        serverPaging: true,
                        serverSorting: true,
                        serverFiltering: true
                    },
                    requestEnd: function(e) {
                        if (e.type != undefined ) {
                            if ( e.type === 'read' ) {
                            }
                        }                            
                    },     
                    type: "odata", //Important!!!!
                    schema: {
                        data: "d.Data",
                        total: "d.Count",
                        model: {
                            id: "PropertyID",
                            fields: {
                                PropertyID: { type: "string" },
                                PropertyCode: { type: "string" },
                                PropertyName: { type: "string" }
                            }
                        }
                    }
                },
                dataBound: onDataBound,
                sortable: true,
                resizable: true,
                height: 380,
//                selectable: "row",
                toolbar: [ { name: 'excel'}],
                excel: {
                    fileName: "Promotion Document Property Include List.xlsx",
                    filterable: true
                },
                batch: true,
                columns: [{ title: '', headerTemplate: '<input type="checkbox" id="checkAll" onclick="updateAll(this)"/>', template: "<input type='checkbox'  class='check-box'  #= LineID ? 'checked=checked' : '' # enabled='' />" ,width:25 },
                            { field: "PropertyDetailID", title: "Property Detail ID", width: 100, hidden: true },
                             { field: "LineID", title: "Line ID", width: 100, hidden: true },
                            { field: "PropertyDetailCode", title: "Property Detail Code", width: 200, hidden: true },
                            { field: "PropertyDetailName", title: "Detail", width: 270}
                            ]
            }).data("kendoGrid");
             //bind click event to the checkbox
        gridDetail.table.on("click", ".check-box" , updateLink);
        //onDataBound
        function onDataBound(e) {
			var view = this.dataSource.view();
            var count  = view.length;
            var checkCount =0;
			for(var i = 0; i < view.length;i++){
            var  dataItem = view[i];
            if(dataItem.LineID!="")
            {

                        checkCount++;
                         this.tbody.find("tr[data-uid='" + view[i].uid + "']")
						.addClass("k-state-selected")
						.find(".checkbox")
						.attr("checked","checked");
		        }
			}		
            if(count == checkCount && count >0)
            {
                 $("#checkAll").prop("checked", true);
            }
            else{
             $("#checkAll").prop("checked", false);

            }
		}
        $("#showSelection").bind("click", function () {
            var checked = [];
            for(var i in checkedIds){
                if(checkedIds[i]){
                    checked.push(i);
                }
            }

        });
      
    //on click of the checkbox:
    function selectRow() {
    
        var checked = this.checked,
        row = $(this).closest("tr"),
        dataItem = gridDetail.dataItem(row);
        checkedIds[dataItem.id] = checked;
        if (checked) {
            //-select the row
            row.addClass("k-state-selected");
            } else {
            //-remove selection
            row.removeClass("k-state-selected");
        }
    }
        });
    </script>
    <h3>  &nbsp;Document <span class="k-icon k-i-arrowhead-e"></span>Property Include</h3>
     <h2 style="display:none;">
        Promotion:&nbsp;
        <asp:Label ID="lblPromotionCode" runat="server"></asp:Label>
        -
        <asp:Label ID="lblPromotionName" runat="server"></asp:Label>
        <asp:HiddenField ID="lblPromotionID" runat="server"></asp:HiddenField>
    </h2>
    <table style="width:100%">
        <tr>
            <td>
                <div id="grid">
                </div>
            </td>
            <td>
                <div id="gridDetail">
                </div>
            </td>
        </tr>
    </table>
</asp:Content>
